'''
Created on 5 Nov 2014

@author: User
'''
from main.data import mylog
import os;
from my_enums import Country;
import logging;
usaNames = None;
ukNames = None;

def getUkCodes():
    """ Get a list of all UK FTSE Stock codes """
    url = "../../resources/codes/";
    return _getCodes(url+"ftse.csv");

def getUsaCodes():
    """ Get a list of 3000 USA Stock Codes """
    url = "../../resources/codes/";
    return _getCodes(url+"russel3000.csv");


def _getCodes(fullurl):
    try:
        filep = open(fullurl).read();
        print filep;
        return filep.split(",");
        
    except Exception as e:
        mylog.error(e);
        
def getNameByStock(stock):
    return getNameByCode(stock.code, stock.country);

def getNameByCode(code,country):
    """ Searches for the stocks name by the code given """
    #os.chdir("/")
    mylog.debug("Current Dir: "+os.getcwd());
    
    names = [];
    if country == Country.UK:
        url = "../../resources/codes/ftse_names.txt";
        filep= open(url);
        for line in filep:
            arr = line.split(",");
            if len(arr)<2:
                mylog.warn("parsing names");
            mylog.debug("Testing {0} against {1}".format(arr[1],code));    
            if code.upper() == arr[1].strip():
                mylog.debug("Name found: " + arr[1]);
                return arr[0];
    
    elif country == Country.USA:
        url = "../../resources/codes/russel_names.txt";
        filep= open(url);
        for line in filep:
            
            arr = line.split(" ");
            mylog.debug("Array: " + str(arr));
            if len(arr)<2:
                mylog.debug("Array less than two, not checking: " + str(line));
                continue;
            mylog.debug("Testing {0} against {1}".format(arr[-2],code));
            if code.upper() == arr[-2]:
                arr.pop();
                arr.pop();
                name = "";
                
                for word in arr:
                    name+=word + " ";
                mylog.info("Found instrument name: " + str(arr))
                return str(name);
            
             
    else:
        mylog.error("getNameByCode() : Coudln't find Country: " + str(country));
        return None;
    
    filep = open(url);
    
    
    
    